package chain

import (
	"awesomeProject1/pkg/chain"
	"github.com/simplechain-org/client/log"
	"github.com/simplechain-org/go-simplechain/p2p"
	"strings"
)

func (s *service) GetNodeInfo() (*p2p.NodeInfo, error) {
	return s.chainClient.GetNodeInfo()
}

func (s *service) GetAllNodes(roleType int, from string) ([]string, error) {
	return s.chainClient.GetAllNodes(roleType, from)
}

func (s *service) PeerCount() (int64, error) {
	return s.chainClient.PeerCount()
}

func (s *service) GetNodesOnChainOnline() ([]*chain.Node, int, error) {
	return s.chainClient.GetNodesOnChainOnline()
}

// IsNodeOnline 检查节点是否在线
// 其实这个方法有缺陷，如果节点不是全部两两相连的情况，这个方法的结果就不准确
func (s *service) IsNodeOnline(nodeId string) bool {
	peers, err := s.chainClient.Peers()
	if err != nil {
		log.Error(err.Error())
		return false
	}
	for _, node := range peers {
		if strings.Contains(node.Enode, nodeId) {
			temp := strings.Split(node.Enode, "@")
			if len(temp) > 0 {
				if strings.EqualFold(strings.ToLower(temp[0]), strings.ToLower(nodeId)) {
					return true
				}
			}
		}
	}
	return false
}

func (s *service) NodeId() (*chain.SimpleNodeInfo, error) {
	return s.chainClient.NodeId()
}
